package com.help10000.rms.ui.activitys

import android.os.Bundle
import com.amir.common.beans.GatheringCodeData
import com.amir.common.beans.PayResultData
import com.amir.common.utils.ImageHelper
import com.amir.common.utils.SavePicUtils
import com.amir.common.utils.ToastUtil
import com.help10000.rms.R
import com.help10000.rms.common.ExecutorServiceManager
import com.help10000.rms.mvp.presenter.GatheringCodePresenter
import com.help10000.rms.mvp.view.GatheringCodeView
import com.help10000.rms.ui.base.BaseActivity
import com.help10000.rms.ui.utils.PageUtils
import kotlinx.android.synthetic.main.activity_gathering_code.*
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit

/**
 * 收款码
 */
class CashCodeActivity : BaseActivity<GatheringCodePresenter, GatheringCodeView>(),
    GatheringCodeView {
    override fun getlayoutId(): Int {
        return R.layout.activity_gathering_code
    }

    var codeReceived: Boolean = false
    override fun initView() {

    }

    override fun initData(savedInstanceState: Bundle?) {
        val RepairId = intent.getStringExtra("RepairId")
        val money = intent.getFloatExtra("money", 0f)
        tv_money.text = "¥ ${money}"
        mPresenter.gathingCode(RepairId, money)
    }

    override fun initListener() {
        super.initListener()
        iv_qrcode.setOnLongClickListener {
            SavePicUtils.getHttpBitmap(qrCodeUrl)
            true;
        }
    }

    override fun createPresenter(): GatheringCodePresenter {
        return GatheringCodePresenter(this)
    }

    var qrCodeUrl = ""
    var future: ScheduledFuture<*>? = null
    override fun codeSuccess(data: GatheringCodeData) {
        if (data.QRCode.isNullOrEmpty()) {
            ToastUtil.show("获取二维码失败")
            return
        }
        codeReceived = true
        this.qrCodeUrl = "${data.QRCode}"
        ImageHelper.displayImage(mContext, this.qrCodeUrl, iv_qrcode)
        future = ExecutorServiceManager.SCHEDULE_THREAD_EXECUTOR.scheduleAtFixedRate(
            {
                runOnUiThread {
                    mPresenter.checkPayResult(data.OrderId)
                }
            },
            5,
            3,
            TimeUnit.SECONDS
        )
    }

    override fun showLoading() {
        if (!codeReceived) {
            super.showLoading()
        }
    }

    override fun onDestroy() {
        future?.cancel(true)
        super.onDestroy()
    }

    override fun payResult(data: PayResultData) {
        if (data.PayResult != 2) {
            future?.cancel(true)
            PageUtils.jumpToResult(
                this,
                OrderActivity::class.java,
                data.PayResult == 1,
                if (data.PayResult == 1) "支付成功" else "支付失败"
            )
            finish()
        }

    }
}